import { Prefab } from 'cc';
import { UITransform } from 'cc';
import { instantiate } from 'cc';
import { Vec2 } from 'cc';
import { find, Sprite, SpriteFrame,tween,Tween,UIOpacity,Game,game as gameCCD, _decorator, Component, Label, Node ,Vec3 } from 'cc'
import { App } from '../../../App';
import AbstractComponent from '../../../base/AbstractComponent';
import { EventConst } from '../../../common/Common';
import CommConst from '../../../const/CommConst';
import { MultiRule } from '../../../hall/multiplay/MultiRule';
import wsTool from '../../../net/ws';
import { LoadMg } from '../../../tools/LoadMg';
import { loadCommonPreFab, showGameActionPoint, showGameMulitExit, showGameMulitUserDetail, showLuckyBallRule, showTip, showTipBox } from '../../../tools/PopuUp';
import UtilTool from '../../../tools/UtilTool';
import { EnergyBar } from '../EnergyBar';
import { GameBaseModel } from '../GameBaseModel';
import { ACTION_POINT_R, SYSTEM_ADDRESS } from '../GameManage';
import { GameModel } from '../model/GameModel';
import { GameModel3 } from './GameModel3';
import { GameMulitUser } from './GameMulitUser';
const { ccclass, property } = _decorator;

// 游戏2D界面
@ccclass('GameLayer3')
export class GameLayer3 extends Component {
    @property(Node)
    bg_fight : Node = null

    @property(Label)
    timeLabel : Label = null

    @property(Node)
    roleNodeSpr = []

    @property(Prefab)
    ball_item : Prefab = null

    // 球节点数组
    private ballNodes = []
    // 倒计时剩余时间
    private countdown = 0

    onLoad() {
    //     gameCCD.on(Game.EVENT_HIDE, function(){
    //         if (this.node==null) return
    //         if(!this.isBackGround){
    //             this.isBackGround = true;
    //             UtilTool.printLog("切换后台");
                
    //         }
    //     }.bind(this));
    //     gameCCD.on(Game.EVENT_SHOW, function(){
    //         if (this.node==null) return
    //         if(this.isBackGround){
    //             UtilTool.printLog("切换前台");    
    //             this.isBackGround = false;
    //             this.reqGameData()
    //         }
    //     }.bind(this));
    }

    start() {
        let gameView = App.Model.gameView as GameModel3
        // 断线重连的处理
        if (App.Model.gameManage.isReconnectAndGameing() || App.Model.gameManage.isWatchGame) {
            gameView.setHoleSwitch(true)
        }
        else {
            // 关闭球洞（系统出杆需要关闭球洞）
            find("holeNode",this.node).active = false
            setTimeout(() => {
                // 获取球洞列表
                let roleNodeList = gameView.roleNodeList
                for (let i = 0; i < roleNodeList.length; i++) {
                    let item = roleNodeList[i]
                    if (item) {
                        let localPos = gameView.World3DToLocal(item.worldPosition)
                        if (this.roleNodeSpr[i]) {
                            this.roleNodeSpr[i].setPosition(localPos.x, localPos.y)
                        }
                    }
                }

                gameView.setHoleSwitch(false)
            }, 100)
        }

        // 观战的处理
        let Btn_giveup = find("Btn_giveup",this.bg_fight)
        let Btn_details = find("Btn_details",this.bg_fight)
        let Btn_quit = find("Btn_quit",this.bg_fight)
        let Btn_watching = find("Btn_watching",this.bg_fight)
        if (App.Model.gameManage.isWatchGame){
            Btn_giveup.active = false
            Btn_details.active = false
            Btn_quit.active = true
            Btn_watching.active = true
        }
        else{
            Btn_giveup.active = true
            Btn_details.active = true
            Btn_quit.active = false
            Btn_watching.active = false
        }

        this.setCurrentPlayer()
        this.setTimeAction(-1)

        this.setActionPoint(new Vec2(0,0))

        //更新作用点位置
        App.Event.on(EventConst.ACTION_BALL_POINT,(data)=>{
            this.setActionPoint(data)
        },this)
    }

    update(deltaTime: number) {
        
    }

    /**
     * 设置当前击打玩家
     */
    setCurrentPlayer(nickname = "", address = UtilTool.getShortWalletAddr(SYSTEM_ADDRESS)) {
        find("curUserLabel",this.bg_fight).getComponent(Label).string = App.language.getLanguageLab(148) + UtilTool.formatNickOrAddress({"nickname":nickname, "address":address})
    }

    /* 更新自己的球 */
    updataSelfBall(userObj:GameMulitUser) {
        let ballList = userObj.ballList
        let ballSlot = find("bg_fight/ballSlot",this.node)
        let bigDict = App.Scene.getRes("images/ball2D")
        // let spDict = App.Scene.getRes("images/ball2D_2")

        for (let i = 0; i < ballList.length; i++) {
            let num = ballList[i]
            
            let ballNode = this.ballNodes[i]
            if (ballNode) {
                ballNode.getComponent(Sprite).spriteFrame = bigDict["ball2d_" + num]
            }
            else {
                let node = instantiate(this.ball_item)
                ballNode = node
                node.getComponent(Sprite).spriteFrame = bigDict["ball2d_" + num]
                node.parent = ballSlot
                node.getComponent(UITransform).setContentSize(60,60)
                this.ballNodes.push(node)
            }
            
            let posx = UtilTool.getSortPosX(ballList.length, 60, i)
            ballNode.setPosition(posx, 0)
        }

        // 删除多余的球
        let len = this.ballNodes.length
        for (let i = len-1; i >= 0; i--) {
            let node = this.ballNodes[i]
            if (i >= ballList.length) {
                this.ballNodes.splice(i,1)
                node.removeFromParent()
            }
        }
    }

    /**
     * 设置倒计时动画
     * @param countdown 剩余倒计时时间 秒
     */
    setTimeAction(countdown=0) {
        if (this.timeLabel == null) {
            return
        }

        if (countdown==-1) {
            this.timeLabel.node.active = false
            return
        }
        this.timeLabel.node.active = true

        this.countdown = countdown
        UtilTool.timeCountdown3(this.timeLabel, countdown, (type,time=0)=>{
            if (type==1) {
                this.countdown = time

                if (this.countdown <=1) {
                    // 时间倒计时还剩1秒的时候不能请求击球
                    let gameView = App.Model.gameView as GameModel3
                    gameView.cueCtrl.isHitBall = false
                }
            }
            else if (type==2) {

            }
        }) 
    }

    /**
     * 停止倒计时
     */
    stopTimeSchedule() {
        Tween.stopAllByTarget(this.timeLabel.node)

    }

    // 重置进度条
    resetProgress() {
        find("energyBar",this.node).getComponent(EnergyBar).resetProgress()
    }

    /** 
     * 点击查看详情
      */
    clickLookAtDetails() {
        App.Audio.playOneShot("click")
        let gameView = App.Model.gameView as GameModel3
        showGameMulitUserDetail(gameView.viewNode)
    }
    
    /** 
     * 点击认输
      */
    clickGiveUp() {
        App.Audio.playOneShot("click")
        let gameView = App.Model.gameView as GameModel3
        showGameMulitExit(gameView.viewNode)
    }

    /** 
     * 退出观战
      */
    clickWatch() {
        App.Audio.playOneShot("click")
        let gameView = App.Model.gameView as GameModel3
        gameView.reqQuitWatchMsg()
    }

    protected onDestroy(): void {
        App.Event.off(EventConst.ACTION_BALL_POINT, this.setActionPoint, this)
    }

    /** 
     * 点击作用点
      */
    clickActionPoint() {
        if (App.Model.gameManage.isWatchGame) {
            // 观战模式不能点击设置作用点
            return
        }

        let gameView = App.Model.gameView as GameBaseModel
        showGameActionPoint(gameView.viewNode)
    }

    /** 
     * 设置作用点
      */
    setActionPoint(pos) {
        let ratio = 50 / ACTION_POINT_R
        let point = find("actionBall/redpoint",this.node)
        point.setPosition(pos.x * ratio, pos.y * ratio)

        if (pos.x == 0 && pos.y == 0) {
            App.Model.gameManage.ballActionDial = 0
            App.Model.gameManage.setActionPoint(pos)
            App.Event.emit(EventConst.GAME_HIT_ACTIONVIEW)
        }
    }

    // 显示规则
    async onBtnQuestion() {
        App.Audio.playOneShot("click")
        let node = await loadCommonPreFab("prefabs/hall/multiplay/multiRule", null)
        node.getComponent(MultiRule).setGameType(0)
    }

}

